package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/wmdng/jlink"
	"gitee.com/wmdng/lua"
	"gitee.com/wmdng/lua/ast"
	"gitee.com/wmdng/lua/util"
)

var (
	gjk *jlink.Jlink
)

func lxrun(l *lua.State) int {
	snm := l.ToString(1)
	snm = filepath.Join(util.Root, "script", snm)
	err := util.Run(l, snm)
	if err != nil {
		fmt.Println("err:", err)
	}
	return 0
}

func main() {
	var his string
	var tln string
	var err error

	jk, err := jlink.TryNewJlink()
	if err != nil {
		fmt.Println("New, err,", err)
		return
	}

	//
	err = jk.Open()
	if err != nil {
		fmt.Println("Open, err,", err)
		return
	}

	defer jk.Close()

	//
	err = jk.Connect()
	if err != nil {
		fmt.Println("connect, err,", err)
		return
	}

	//
	gjk = jk

	l := util.NewState()
	l.Push(lxrun)
	l.SetGlobal("Xrun")
	l.Preload("jlink", Open)

	//
	sc := bufio.NewScanner(os.Stdin)
	his = ""
	fmt.Printf("%d>>\n", l.AbsIndex(-1))
	for sc.Scan() {

		//
		tln = strings.TrimSpace(sc.Text())
		if len(tln) == 0 {
			continue
		}

		//
		his = his + tln + "\n"
		err = l.LoadString(his, "=stdin", 0)
		if err != nil {
			aer := err.(*ast.Error)
			if aer.IsNotSegment() {
				continue
			}

			// other err, discard lines
			fmt.Println("err: ", err)
			fmt.Printf("%d>>\n", l.AbsIndex(-1))
			his = ""

		} else {

			// excute
			if msg := l.PCall(0, 0, true); msg != nil {
				fmt.Printf("::%v\n", msg)
			}

			fmt.Printf("%d>>\n", l.AbsIndex(-1))
			his = ""
		}

	}

	if err = sc.Err(); err != nil {
		fmt.Println("err:", err)
	}

	// util.Run(l, "main.lua")
	fmt.Println("succ")
}
